package spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class ApplicationContext {

    private Class configClass;

    // 创建一个map
    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,Object> singltonObjects = new ConcurrentHashMap<>();

    private ArrayList<BeanPostProcessor> beanPostProcessorsList = new ArrayList<>();

    // spring容器启动需要做什么
    public ApplicationContext(Class configClass) {
        this.configClass = configClass;
        // 扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan)configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value(); // "service"
            path = path.replace(".", "/"); // "/service"
            // 拿到类加载器
            ClassLoader classLoader = ApplicationContext.class.getClassLoader();
            // 拿到对应文件夹
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    // 拿到文件的绝对路径
                    String fileName = f.getAbsolutePath();
                    // 只拿到 class文件
                    if (fileName.endsWith(".class")) {
                       // 判断对应类上有没有component注解
                        String className = fileName.substring(fileName.indexOf("service"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");
                        try {
                            // 类名格式 service.AppConfig
                            Class<?> clazz = classLoader.loadClass(className);
                            if (clazz.isAnnotationPresent(Component.class)) {

                                if (BeanPostProcessor.class.isAssignableFrom(clazz)){
                                    BeanPostProcessor o = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorsList.add(o);
                                }

                                Component componentAnnotation = clazz.getAnnotation(Component.class);
                                String beanName = componentAnnotation.value();

                                if ("".equals(beanName)){
                                    beanName= Introspector.decapitalize(clazz.getSimpleName());
                                }
                               // 单例bean 多例bean
                                BeanDefinition beanDefinition = new BeanDefinition();
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    String scope = scopeAnnotation.value();
                                    if ("prototype".equals(scope)) {
                                        beanDefinition.setScope("prototype");
                                    } else {
                                        beanDefinition.setScope("singleton");
                                    }
                                    beanDefinition.setType(clazz);
                                }else {
                                    beanDefinition.setScope("singleton");
                                    beanDefinition.setType(clazz);
                                }
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            throw new RuntimeException(e);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }

        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            // 如果是单例Bean则创建单例bean
            if ("singleton".equals(beanDefinition.getScope())) {
                Object bean = createBean(beanName,beanDefinition);
                singltonObjects.put(beanName,bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        // 创建bean
        Class clazz = beanDefinition.getType();
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(Autowired.class)){
                    declaredField.setAccessible(true);
                    declaredField.set(instance,getBean(declaredField.getName()));
                }
            }
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return instance;
    }


    public Object getBean(String beanName) {
        // 多例bean直接创建 单例bean从容器中拿
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition== null){
            throw new NullPointerException();
        }else if ("prototype".equals(beanDefinition.getScope())){
            return createBean(beanName,beanDefinition);
        }else if ("singleton".equals(beanDefinition.getScope())){
            // 单例情况
            Object bean = singltonObjects.get(beanName);
            if (bean == null){
                // 创建单例bean
                bean = createBean(beanName, beanDefinition);
                singltonObjects.put(beanName,bean);
            }
            return bean;
        }
        return null;
    }
}
